package com.lyl.syt.modules.mongodb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.lyl.syt.model.hosp.Department;
import com.lyl.syt.vo.hosp.ScheduleOrderVo;
import org.joda.time.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lyl.syt.common.exception.YyghException;
import com.lyl.syt.common.result.ResultCodeEnum;
import com.lyl.syt.model.hosp.BookingRule;
import com.lyl.syt.model.hosp.Hospital;
import com.lyl.syt.model.hosp.Schedule;
import com.lyl.syt.modules.mongodb.dao.ScheduleDao;
import com.lyl.syt.modules.mongodb.service.DepartmentService;
import com.lyl.syt.modules.mongodb.service.HospitalService;
import com.lyl.syt.modules.mongodb.service.ScheduleService;
import com.lyl.syt.vo.hosp.BookingScheduleRuleVo;
import com.lyl.syt.vo.hosp.ScheduleQueryVo;
import lombok.RequiredArgsConstructor;
import org.joda.time.format.DateTimeFormat;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ScheduleServiceImpl implements ScheduleService {
    private final ScheduleDao scheduleDao;
    private final MongoTemplate mongoTemplate;
    private final HospitalService hospitalService;
    private final DepartmentService departmentService;

    @Override
    public void save(Map<String, Object> paramMap) {
        String json = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(json, Schedule.class);

        //根据医院编号和排班编号查询
        Schedule scheduleExist = scheduleDao.getByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        if (scheduleExist != null) {
            schedule.setCreateTime(new Date());
        }
        schedule.setUpdateTime(new Date());
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        scheduleDao.save(schedule);
    }

    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo queryVo) {
        //创建pageAble对象，设置分页参数
        Pageable pageable = PageRequest.of(page - 1, limit);

        //创建example对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        //构建查询对象
        Schedule schedule = new Schedule();
        BeanUtil.copyProperties(queryVo, schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);
        Example<Schedule> example = Example.of(schedule, matcher);
        return scheduleDao.findAll(example, pageable);
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        //根据医院编号和排班编号查询数据
        Schedule schedule = scheduleDao.getByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleDao.deleteById(schedule.getId());
        }
    }

    @Override
    public Map<String, Object> getScheduleRule(Long page, Long limit, String hoscode, String depcode) {
        //1. 根据医院编号和科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode);

        //2. 根据工作日workDate日期进行分组查询
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")
                        .first("workDate")
                        .as("workDate")
                        //统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );

        AggregationResults<BookingScheduleRuleVo> aggResult = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> ruleList = aggResult.getMappedResults();

        //分组查询之后得到总的纪录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        int size = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class).getMappedResults().size();

        //处理日期对应星期几
        ruleList.forEach(t -> {
            String week = DateUtil.dayOfWeekEnum(t.getWorkDate()).toChinese();
            t.setDayOfWeek(week);
        });

        //组装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("bookingScheduleRuleList", ruleList);
        map.put("total", size);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hospitalService.getByHoscode(hoscode).getHosname());

        map.put("baseMap", baseMap);
        return map;
    }

    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        //根据参数查询mongodb
        List<Schedule> list = scheduleDao.findByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, DateUtil.parse(workDate).toJdkDate());
        //设置其他值：医院名称，科室名称，日期对比星期
        list.forEach(this::packageSchedule);
        return list;
    }


    @Override
    public Map<String, Object> getBookingScheduleRules(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> map = new HashMap<>();
        //获取预约规则
        //根据医院编号，获取医院规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        Assert.notNull(hospital, () -> new YyghException(ResultCodeEnum.DATA_ERROR));
        BookingRule bookingRule = hospital.getBookingRule();

        //获取可预约数据（分页）
        IPage<Date> iPage = getListData(page, limit, bookingRule);
        //获取可预约的规则数据
        List<BookingScheduleRuleVo> voList = getBookingScheduleRuleVoList(page, hoscode, depcode, bookingRule, iPage);

        //封装返回参数
        map.put("bookingScheduleList", voList);
        map.put("total", iPage.getTotal());
        map.put("baseMap", getBookingScheduleRuleVoBaseMap(hoscode, depcode, bookingRule));
        return map;
    }

    @Override
    public Schedule getScheduleById(String scheduleId) {
        Schedule schedule = scheduleDao.findById(scheduleId).orElse(new Schedule());
        packageSchedule(schedule);
        return schedule;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //获取排班信息
        Schedule schedule = getScheduleById(scheduleId);
        Assert.notNull(schedule, () -> new YyghException(ResultCodeEnum.PARAM_ERROR));

        //获取预约规则信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        Assert.notNull(hospital, () -> new YyghException(ResultCodeEnum.PARAM_ERROR));

        BookingRule bookingRule = hospital.getBookingRule();
        Assert.notNull(bookingRule, () -> new YyghException(ResultCodeEnum.PARAM_ERROR));

        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getByHoscode(schedule.getHoscode()).getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());      //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        return scheduleOrderVo;
    }

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleDao.save(schedule);
    }

    //封装请求参数
    private Map<String, String> getBookingScheduleRuleVoBaseMap(String hoscode, String depcode, BookingRule bookingRule) {
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getByHoscode(hoscode).getHosname());
        //科室信息
        Department department = Optional.ofNullable(departmentService.getByHoscodeAndDepcode(hoscode, depcode)).orElse(new Department());
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        return baseMap;
    }

    private List<BookingScheduleRuleVo> getBookingScheduleRuleVoList(Integer page, String hoscode, String depcode, BookingRule bookingRule, IPage<Date> iPage) {
        //当前可预约日期
        List<Date> dateList = iPage.getRecords();
        //获取根据日期为键的排班规则
        Map<Date, BookingScheduleRuleVo> scheduleRuleVoMap = getScheduleVoMapWithDate(hoscode, depcode, dateList);
        //聚合排班规则
        List<BookingScheduleRuleVo> voList = new ArrayList<>();
        int len = dateList.size();
        for (int i = 0; i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo vo = scheduleRuleVoMap.get(date);
            if (vo == null) {
                vo = new BookingScheduleRuleVo();
                vo.setDocCount(0);
                vo.setAvailableNumber(-1);
            }
            vo.setWorkDate(date);
            vo.setWorkDateMd(date);
            //计算预约日期对应的星期
            vo.setDayOfWeek(DateUtil.dayOfWeekEnum(date).toChinese());

            //最后一条记录为即将预约  状态：0 正常 1：即将放号 -1:当天已停止挂号
            boolean isLastPageNum = i == len - 1 && page == iPage.getPages();
            vo.setStatus(isLastPageNum ? 1 : 0);

            //如果当天已经过了停号时间，不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    vo.setStatus(-1);
                }
            }
            voList.add(vo);
        }
        return voList;
    }

    private Map<Date, BookingScheduleRuleVo> getScheduleVoMapWithDate(String hoscode, String depcode, List<Date> dateList) {
        //获取可预约日期里面科室的剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);

        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleRuleVoList = Optional.ofNullable(aggregate.getMappedResults()).orElse(new ArrayList<>());
        //合并数据
        Map<Date, BookingScheduleRuleVo> scheduleRuleVoMap = scheduleRuleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, t -> t));
        return scheduleRuleVoMap;
    }

    private IPage<Date> getListData(Integer page, Integer limit, BookingRule bookingRule) {
        //当天放号时间
        DateTime releaseTime = getDateTime(new Date(), bookingRule.getReleaseTime());
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //如果当天放号时间已经过，预约周期从后一天开始，周期+1
        if (releaseTime.isBeforeNow())
            cycle += 1;
        //获取所有可预约的所有日期，最后一天显示即将放号
        List<Date> dateList = new ArrayList<>();
        for (Integer i = 0; i < cycle; i++) {
            DateTime dateTime = new DateTime().plusDays(i);
            String dataStr = dateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dataStr).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        if (end > dateList.size()) end = dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    private DateTime getDateTime(Date date, String timeStr) {
        String dateTimeStr = new DateTime(date).toString("yyyy-MM-dd") + " " + timeStr;
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeStr);
    }

    //设置其他值：医院名称，科室名称，日期对比星期
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname", hospitalService.getByHoscode(schedule.getHoscode()).getHosname());
        //设置科室名称
        schedule.getParam().put("depname", departmentService.getByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek", DateUtil.dayOfWeekEnum(schedule.getWorkDate()).toChinese());
    }
}
